define(function(require, exports){
  const Handlebars = require('handlebars')
  const $ = require('jquery')
  const earth = require('app/earth')
  const moment = require('moment')
  const {
    customPieChart,
    customHistogram,
    customLineChart,
    customHistogramR,
    sleep, tick, getwh, throttle
  } = require('app/func')

  const tabTypes = ['', '法规', '标准', '技术', '威胁', '新闻事件']

  let inited = false
  let $reportBtn = $('#home-report-btn')
  let $detail = $('#home-report-mask>.detail')
  let $detailCont = $('#home-report-mask>.detail>.cont')
  let $closeBtn = $('#home-report-mask>.detail>.cont>.close')
  let $list
  let $tabs = $('.todayinfo>.tabs :radio')
  let $mask = $('#home-report-mask')
  let $shims = $('#home-report-mask>.shim')
  let $hotkws = $('#page-ecart4>.rchart .hotkws')
  
  let $todaystatus = $('#page-ecart4>.rchart .todaystatus')
  let $detailWithShims = $shims.add($detail)
  
  let tpl_todayInfo = Handlebars.compile($('#home-todayinfo').html())
  let tpl_topicList = Handlebars.compile($('#home-topiclist').html())
  let tpl_reportList = Handlebars.compile($('#tpl-home-reportlist').html())
  let tpl_reportCont = Handlebars.compile($('#tpl-topic-cont').html())
  
  let isDetail = false
  let isMask = false

  $('#page-home>*').addClass('fadeOut')
  //获取月天数
  // 2017 修改time
  var num=0
  var l=0
  $('.time-chose').on('click','label>input',function(){
    $('.point-line').empty()
    num=0;
    //$('.time-axis').css('transform','translateX(0)')
    let oHml='';
  if($(this).val()=="0"){
      l=7
      let m=''
      for(var i=0;i<l;i++){
        switch(i)
        {
          case 0 :
            m ="一"
            break;
          case 1 :
            m ="二"
            break;
          case 2 :
            m ="三"
            break;
          case 3 :
            m ="四"
            break;
          case 4 :
            m ="五"
            break;
          case 5 :
            m ="六"
            break;
          case 6 :
            m ="日"
            break;
          default:
            break;
        }
        if(i<8){
          oHml+="<div class='x'><span>周"+m+"</span></div>"
        }      
      }  
      let oPiot=''
      $.post('api/collection/event',{
        mode:$(this).val(),
      }).then(res=>{
        let w=0;
        let v=null;
        let m=0
        res.obj.map((d)=> {
          let arr=['Mon','Tue','Wed','Thu','Fri','Sat','Sun']
          w=arr.indexOf(d.week)
          if(v==w){
            m++
            if(m>9){
                return 
            }
            v=w+(0.1*m)
          }else{
            v=w
            m=0
          }
          oPiot+="<div class='point' data-id="+d.id+" style=left:"+(v*250+54+v) +'px'+ "></div>"
          v=w
        })
        $('.point-line').empty().append(oPiot)
      })

    }else if($(this).val()=="2"){
      let arr=['一','二','三','四','五','六','七','八','九','十','十一','十二']
      l=12
      let n=""
      for(var j=0;j<l;j++){
        n=arr[j]
        oHml+="<div class='x'><span>"+n+"月</span></div>"
      }
      let oPiot=''
      $.post('api/collection/event',{
        mode:$(this).val(),
      }).then(res=>{
          let w=0;
          let v=0;
          let m=0
        res.obj.map((d)=> {
          w=parseInt(d.month)
          if(v==w){
            m++
            if(m>9){
                return 
            }
            v=w+(0.1*m)
          }else{
            v=w
            m=0
          }
          oPiot+="<div class='point'  data-id="+d.id+"  style=left:"+((v-1)*250+80) +'px'+ "></div>"
          v=w
        })
        $('.point-line').empty().append(oPiot)
      })
    }else if($(this).val()=="1"){
      let arrweek=['一','二','三','四','五','六']
      let a=''
      l=6
      for(let k=0;k<l;k++){
        a=arrweek[k]
        oHml+="<div class='x x1'><span>第"+a+"周</span></div>"
      } 
      let oPiot=''
      $.post('api/collection/event',{
        mode:$(this).val(),
      }).then(res=>{
        let w=0;
        let v=0;
        let m=0;
        res.obj.map((d)=> {
          w=parseInt(d.num)
          if(v==w){
            m++
            if(m>9){
              return
            }
            v=w+(0.1*m)
          }else{
            v=w
            m=0
          }
          oPiot+="<div class='point'  data-id="+d.id+"  style=left:"+((v-1)*400+60) +'px'+ "></div>"
          v=w
        })
        $('.point-line').empty().append(oPiot)
      })
    }
    if($(this).val()!="1"){
      $('.time-axis').css('width',l*250+200+'px')
      $('.time-axis').animate({left:'-'+num*250+'px'},100)
      $('.time-wrap .time-axis .axis-line').empty().append(oHml)
    }else{
      $('.time-axis').css('width',l*400+200+'px')
      $('.time-axis').animate({left:'-'+num*400+'px'},100)
      $('.time-wrap .time-axis .axis-line').empty().append(oHml)
    }
  })

  $('.time-wrap').on('click','.time-prev',function(){
    let type=$('.time-chose').find('input[name="timea"]:checked').val()
    if(num<=0){
      return false
    }
    num--
    if(type!=1){
      $('.time-axis').animate({left:'-'+num*250+'px'},100)
    }else{
      $('.time-axis').animate({left:'-'+num*400+'px'},100)
    }
    
  })
  $('.time-next').on('click',function(){
      let type=$('.time-chose').find('input[name="timea"]:checked').val()
      if(type!=1){
        if(num>=(l-5)){
          return false
        }
        num++  
        $('.time-axis').animate({left:'-'+num*250+'px'},100)   
      }else{
        if(num>=(l-3)){
          return false
        }
        num++ 
        $('.time-axis').animate({left:'-'+num*380+'px'},100)
      }
  })
  $('.point-line').on('click','.point',function(){
    clearInterval(timer)
    $('.circle-time').show()
    $('.img').empty()
    let Id=$(this).attr('data-id')
    let timer=setTimeout(function(){
      $.get('api/collection/event/queryById?id='+Id).then(res => {
      let txt=res.obj.memoryContent
      let arrImg=[]
      if(res.obj.urlOne.length>0){
        arrImg.push(res.obj.urlOne)
      }else if(res.obj.urlTwo.length>0){
        arrImg.push(res.obj.urlTwo)
      }else if(res.obj.urlThree.length>0){
        arrImg.push(res.obj.urlThree)
      }
      $.each(arrImg,(item,i)=>{
          $('.img').append('<img src='+i+' />')
      })
      $('.circle-time .info').empty().text(txt)
    })
  },500)
  let L=$(this).css('left')
  let K=parseInt($('.time-axis').css('left'))
  $('.circle-time').css({'opacity':'1','left':(parseInt(L)-(380-K))+10+"px",'bottom':'89px'})
})
  $('.point-line').on('mouseout','.point',function(){
    $('.circle-time').hide()
  })
  $('.time-chose label:eq(0)>input').trigger('click')


  // async function getBigevent(type){

  //   console.log(res.obj)
  //   return res.obj
    
  // }
  exports.routeIn = function(){
    
    $('#wrap').addClass('ecart4')
    $('#page-ecart1').hide()
    $('#webgl-bg-round,#webgl-content,.m-overtop,#page-search').hide()
    $('.head-right-time').show()

    $.get('api/collection/getTodayCollections').then(r => {
      $('#home-topic-all').text(r + '条')
    })
    let activeTab = $('[name=todayinfo-tabs]:checked').data('type')
    renderTodayInfo(activeTab)
    renderLcharts()
    renderRchart()
    renderTopicWords()
    renderRtype()
    // earth.timeline.hide()
    $('#head-right-search>input').on('keypress',function(event){
      if(event.keyCode=="13"){
        let val = $(this).val()
        if (val) {
          location.hash = 'search'
          sessionStorage.wd = val
          setTimeout(function(){
            $('.searchbtn').click()
          }, 1000)
        }
      }  
    })
    $('.searchbtn').on('click',function(){
      let val = $(this).siblings(':text').val()
      if (val) {
        location.hash = 'search'
        sessionStorage.wd = val
        setTimeout(function(){
          $(this).click()
        }, 1000)
      }
    })
    if(!inited){
      inited = true
      new renderReportList()
      $reportBtn.on('click', throttle(600, onReportBtnClick))
      $mask.on('mousedown', e => e.stopPropagation())
      $mask.on('mousemove', e => e.stopPropagation())
      $mask.on('mouseup', e => e.stopPropagation())
      $tabs.on('change', onTabChange)
      $hotkws.on('click', '>.item', e => {
        return
        $('#head-right-search>input').val(e.currentTarget.innerText)
        $('.searchbtn').click()
      })
      new renderTopicList()
      setInterval(function(){
        let $kws = $('#page-ecart4>.rchart>div>.hotkws>.item')
        $kws.removeClass('active')
        $kws.eq(Math.floor(Math.random() * $kws.length)).addClass('active')
      }, 2000)
    }
  }
  //2017 12 02
  $mask.on('click',function(){
    $mask.removeClass('active')
    $mask.hide()
    $closeBtn.trigger('click')
    isMask=false
  })
  $mask.on('click','.right','.left',function(e){
    e.stopPropagation()
  })
  $mask.on('click','.left','.left',function(e){
    e.stopPropagation()
  })
  $mask.on('click','.detail','.left',function(e){
    e.stopPropagation()
  })
  //2017 12 02
  exports.routeOut = function(){
    $('#wrap').removeClass('ecart4')
    $('#page-home>*').addClass('fadeOut')
    // earth.timeline.hide()
    $('#head-right-search>input').off('keypress')
    $('.searchbtn').off('click')
  }

  function onTabChange(){
    let i = tabTypes.indexOf($tabs.filter(':checked').val())
    renderTodayInfo(i)
  }

  async function onReportBtnClick(){
    if(!isMask){
      $mask.show()
      $mask.addClass('active')
      $list.addClass('enter')
      await sleep(500)
      $list.removeClass('enter')
    }else{
      $mask.removeClass('active')
      await sleep(500)
      $mask.hide()
    }
    isMask = !isMask
  }

  async function renderTodayInfo(type){
    let res = await $.post('api/collection/getTodayInfos', {
      startTime: moment().subtract(3, 'months').format('YYYY-MM-DD HH:mm:ss'),
      endTime: moment().format('YYYY-MM-DD HH:mm:ss'),
      type,
      currentPage: 1,
      page: 10
    })
    let data = {}
    data.news = res.obj.map(d => ({
      cid: d.id,
      title: d.title,
      time: moment(d.createTime).format('MM-DD HH:mm'),
      cont: d.content,
      from_country: d.country,
      from_media: d.webSite,
      category: tabTypes[d.type]
    }))
    $('.tabcont').html(tpl_todayInfo(data))
    $('.tabcont').niceScroll({
      cursorcolor :"",
      autohidemode: true ,
      cursoropacitymax:0,
      cursorwidth :0,
      touchbehavior:false,
      cursoropacitymin: 0
    })
  }
  function renderLcharts(){
    $.post('api/collection/getCollectionByTime', {
      startTime: moment().subtract(3, 'months').format('YYYY-MM-DD HH:mm:ss'),
      endTime: moment().format('YYYY-MM-DD HH:mm:ss'),
    }).then(res => {
      let dataset = res.obj.map(d => d.num)
      customHistogram('#page-home>.lchart .lchart1', dataset)
      customHistogram('#page-ecart4>.lchart .lchart1', dataset)
    })
    $.post('api/collection/getCollectionByCountry', {
      startTime: moment().subtract(3, 'months').format('YYYY-MM-DD HH:mm:ss'),
      endTime: moment().format('YYYY-MM-DD HH:mm:ss'),
    }).then(res => {
      let dataset = res.obj.map(d => ({label: d.country, count: d.num}))
      customPieChart('#page-home>.lchart .lchart2', dataset)
      customPieChart('#page-ecart4>.lchart .lchart2', dataset)
    })
    $.post('api/collection/getCollectionByType', {
      startTime: moment().subtract(3, 'months').format('YYYY-MM-DD HH:mm:ss'),
      endTime: moment().format('YYYY-MM-DD HH:mm:ss'),
    }).then(res => {
      let dataset = res.obj.map(d => ({label: tabTypes[d.type], count: d.num}))
      customPieChart('#page-home>.lchart .lchart3', dataset)
      customPieChart('#page-ecart2>.lchart .lchart3', dataset)
    })
  }
  async function renderRtype(){
    const types = ['未编辑', '已编辑', '已翻译', '待审批', '审批通过', '审批驳回']
    let res = await $.post('api/collection/getCollectionByStatus', {
      startTime: moment().subtract(3, 'months').format('YYYY-MM-DD HH:mm:ss'),
      endTime: moment().format('YYYY-MM-DD HH:mm:ss'),
    })
    let html = types.map((d, i) => {
      let tmp = res.obj.filter(d => d.status == i)[0]
      let num = tmp ? tmp.num : 0
      return `<div class="item">${d}情报：${num}</div>`
    }).join('')
    $todaystatus.html(html)
  }
  async function renderRchart(){
    let res = await $.post('api/collection/getCollectionByWebSite', {
      startTime: moment().subtract(3, 'months').format('YYYY-MM-DD HH:mm:ss'),
      endTime: moment().format('YYYY-MM-DD HH:mm:ss'),
    })
    let dataset = res.obj.map(d => [d.webSite, d.num])
    customHistogramR('#page-ecart4>.rchart .topchart', dataset)
  }

  function topicCharts(type, sel, rawdata){
    if(type == 'Country'){
      customPieChart(sel, rawdata.map(d => ({
        label: d.country,
        count: d.num
      })))
    }else if(type == 'PoTime'){
      let dataset = [rawdata.map((d, i) => [i, d.num])]
      dataset[0].unshift([0, 0])
      customLineChart(sel, dataset)
    }else if(type == 'WebSite'){
      let dataset = rawdata.map(d => [d.webSite, d.num])
      customHistogramR(sel, dataset)
    }
  }

  async function renderTopicWords(){
    let res = await $.get('api/collection/getHotKeywords')
    let html = res.obj.slice(0, 12).map(d => `<div class="item">${d}</div>`).join('')
    $hotkws.html(html)
  }
  
  class renderTopicList{
    constructor(){
      this.topicPage = 1
      this.$page = $('#page-home')
      this.$page.on('mousewheel', '.topicblock', throttle(1000, this.onmousewheel.bind(this)))
      this.init()
    }
    async getCurrentPage(cls){
      let topicList = await $.post('api/topic/getTopicList', {currentPage: this.topicPage, page: 2})
      let charts = topicList.obj.map(e =>
        ['Country', 'PoTime', 'WebSite'].map(d => 
          $.post('api/topic/getTopicInfoNumBy' + d, d == 'WebSite' ? {
            id: e.id,
            startTime: moment().subtract(3, 'months').format('YYYY-MM-DD HH:mm:ss'),
            endTime: moment().format('YYYY-MM-DD HH:mm:ss'),
          } : {id: e.id}).then(res => ({res: res.obj, tid: e.id, type: d}))
        )
      )
      let newsList = await Promise.all(topicList.obj.map(o =>
        $.post('api/topic/getTopicInfoList', {currentPage: 1, page: 4, topicId: o.id})
      ))
      let data = {
        topics: topicList.obj.map((e, i) => ({
          name: e.topicName,
          num: e.topicNum,
          tid: e.id,
          news: newsList[i].obj.map(o => ({
            tid: o.id,
            title: o.infoTitle,
            time: moment(o.poTime).format('MM-DD HH:mm')
          })),
          nodata: newsList[i].obj.length == 0
        }))
      }
      let $el = $(tpl_topicList(data))
      $el.addClass(cls)
      this.$page.append($el)
      charts.forEach((e, i) =>
        e.forEach(o => o.then(obj => {
          let sel = `#page-home>.topicblock:last-child>.item:nth-child(${i + 1})>.charts>.${obj.type}`
          topicCharts(obj.type, sel, obj.res)
        }))
      )
      await Promise.all(charts.reduce((a, b) => a.concat(b)))
      return $el
    }
    async getall(){
      let all_list = await $.post('api/topic/getTopicList', {currentPage: 1, page: 999})
      this.all = all_list.obj.length
    }
    async init(){
      await this.getall()
      this.$topicblock = await this.getCurrentPage()
    }
    async pre(){
      this.topicPage -= 1
      if(this.topicPage <= 0){
        await this.getall()
        this.topicPage = Math.ceil(this.all / 2)
      }
      let $el = await this.getCurrentPage('pre')
      $el.removeClass('pre')
      this.$topicblock.addClass('next')
      await sleep(500)
      this.$topicblock.remove()
      this.$topicblock = $el
    }
    async next(){
      this.topicPage += 1
      await this.getall()
      if(this.topicPage > Math.ceil(this.all / 2)){
        this.topicPage = 1
      }
      let $el = await this.getCurrentPage('next')
      $el.removeClass('next')
      this.$topicblock.addClass('pre')
      await sleep(500)
      this.$topicblock.remove()
      this.$topicblock = $el
    }
    async onmousewheel(e){
      e.originalEvent.deltaY < 0 && this.pre()
      e.originalEvent.deltaY > 0 && this.next()
    }
  }

  class renderReportList{
    constructor(){
      this.page = 1
      this.$pagebtns = ['left', 'right'].map(d => $(`#home-report-mask>.${d}`))
      this.$reportCont = $('#home-report-mask>.detail>.cont>.content')
      this.list = []
      this.current = 0
      this.init()
    }
    async init(){
      this.$pagebtns.forEach(($el, i) => 
        $el.on('click',throttle(600, this[`on${i ? 'R' : 'L'}btnClick`].bind(this))))
      $list = await this.getListPage()
      $mask.append($list)
      $mask.on('click', '>.list>.item', throttle(600, this.onMaskClickListItem.bind(this)))
      $closeBtn.on('click', throttle(600, this.onCloseBtnClick.bind(this)))
    }
    async getListPage(){
      let res = await $.post('api/report/getReportList', {
        currentPage: this.page,
        pageSize: 12
      })
      this.pages = res.pages
      let btnsStatus = [res.obj.hasPreviousPage, res.obj.hasNextPage]
      this.$pagebtns.forEach(($el, i) => 
        $el[`${btnsStatus[i] ? 'remove' : 'add'}Class`]('hide'))
      this.list = res.obj.list.map((d, i) => ({
        index: i,
        rid: d.id,
        title: d.bodyTitle,
        number: d.number,
        measurementName: d.measurementName,
        createTime: moment(d.createTime).format('YYYY年MM月DD日'),
        content: d.bodyContent,
        reportName: d.reportName,
        sendName: d.sendName,
      }))
      let m = {item: this.list}
      return $(tpl_reportList(m))
    }
    async onRbtnClick(){
      if(isDetail){
        $detailWithShims.addClass('up')
        $detailCont.addClass('hide')
        await sleep(400)
        this.current += 1
        if(this.current == this.list.length) this.current = 0
        this.updateContent()
        $detailWithShims.css('transitionDuration', '0s')
        $detailWithShims.removeClass('up')
        $detailCont.removeClass('hide')
        await sleep(400)
        $detailWithShims.css('transitionDuration', '')
      }else{
        this.page += 1
        if(this.page == this.pages + 1) this.page = this.pages
        let $newList = await this.getListPage()
        $newList.addClass('flyright')
        $mask.append($newList)
        await sleep(80)
        $newList.removeClass('flyright')
        $list.addClass('flyleft')
        await sleep(400)
        $list.remove()
        $list = $newList
      }
    }
    async onLbtnClick(){
      if(isDetail){
        $detailWithShims.css('transitionDuration', '0s')
        $detailWithShims.addClass('up')
        $detailCont.css('transitionDuration', '0s')
        $detailCont.addClass('hide')
        await tick()
        $detailWithShims.css('transitionDuration', '')
        $detailCont.css('transitionDuration', '')
        $detailWithShims.removeClass('up')
        await sleep(400)
        this.current -= 1
        if(this.current == -1) this.current = this.list.length - 1
        this.updateContent()
        $detailCont.removeClass('hide')
      }else{
        this.page -= 1
        if(this.page == 0) this.page = this.pages
        let $newList = await this.getListPage()
        $newList.addClass('flyleft')
        $mask.append($newList)
        await sleep(80)
        $newList.removeClass('flyleft')
        $list.addClass('flyright')
        await sleep(400)
        $list.remove()
        $list = $newList
      }
    }
    updateContent(){
      let dataset = this.list[this.current]
      //this.$reportCont.html("11111")
    }
    async onMaskClickListItem(e){
      e.stopPropagation()
      let $item = $(e.currentTarget)
      let rid = $item.data('idx')
      this.current = rid
      this.updateContent()
      this.$pagebtns.forEach($el => {
        $el.data('last', $el.hasClass('hide'))
        $el.removeClass('hide')
      })
      // 在改变列表item之前获取它的宽高
      let rect = $item[0].getBoundingClientRect()
      let wh = getwh()
      $item.siblings().addClass('fadeOut')
      $item.addClass('fadeCont')
      $detailCont.addClass('hide')
      await sleep(500)
      $list.hide()
      $item.siblings().removeClass('fadeOut')
      $item.removeClass('fadeCont')
      let left =  (rect.left + rect.width / 2) / wh.r - wh.w / 2
      let top = (rect.top + rect.height / 2) / wh.r - 20 - wh.h / 2
      $detail.css({
        display: 'block',
        transform: `translate(${left}px, ${top}px) scale(0.1792, 0.3626) rotateY(90deg)`
      })
      // 这里用tick时间不够，还是会造成动画过渡消失
      // 实测sleep(60)也会出现，所以这里调到sleep(80)
      // 当然也可能是我机器没显卡的问题，卡帧了
      // 但添加80ms延迟不会对视觉效果造成太大影响
      await sleep(80)
      $detail.css('transform', '')
      await sleep(400)
      $shims.removeClass('hide')
      $detailCont.removeClass('hide')
      isDetail = true
    }

    async onCloseBtnClick(){
      this.$pagebtns.forEach($el => $el.data('last') && $el.addClass('hide'))      
      $shims.addClass('hide')
      $detail.addClass('fadeOut')
      setTimeout(function() {
        $detail.removeClass('fadeOut')
        $detail.hide()
      }, 500)
      $list.show()
      $list.addClass('enter')
      await sleep(80)
      $list.removeClass('enter')
      isDetail = false
    }
  }

})

